package com.lingnan.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;

import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.com.google.common.base.Preconditions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingnan.entity.dto.UserAccountDTO;
import com.lingnan.entity.po.Company;
import com.lingnan.entity.po.CompanyHr;
import com.lingnan.entity.po.JobSeeker;
import com.lingnan.entity.po.UserAccount;
import com.lingnan.entity.vo.Result;
import com.lingnan.redis.RedisUtil;
import com.lingnan.service.AuthUserService;
import com.lingnan.service.impl.UserInfoServiceImpl;
import com.lingnan.utils.EmailApi;
import com.lingnan.utils.LoginUtil;
import com.lingnan.utils.ValidateCodeUtils;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user/")
@Slf4j
@CrossOrigin
public class UserController {

    @Resource
    private AuthUserService authUserDomainService;
    private static final String KEY_WORD = "短信验证码";

    private static final String PHONE_PREFIX = "phoneCode";
    @Resource
    private EmailApi emailApi;
    @Resource
    private RedisUtil redisUtil;
    /*
     */
/**
 * 用户注册
 *//*

    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO, @RequestParam("role") String role) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSONUtil.toJsonStr(authUserDTO));
            }
            checkUserInfo(authUserDTO);
            AuthUser authUser = BeanUtil.copyProperties(authUserDTO, AuthUser.class);
            return Result.ok(authUserDomainService.register(authUser,role));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("注册用户失败");
        }
    }

    */
/**
 * 修改用户信息
 *//*

    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSONUtil.toJsonStr(authUserDTO));
            }
            checkUserInfo(authUserDTO);
            AuthUser authUser = BeanUtil.copyProperties(authUserDTO, AuthUser.class);
            return Result.ok(authUserDomainService.update(authUser));
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("更新用户信息失败");
        }
    }

    */
/**
 * 获取用户信息
 */

    @RequestMapping("getUserInfo")
    public Result<UserAccountDTO> getUserInfo(  ) {
        try {
            return Result.ok(userInfoService.getUserAccountById(Long.valueOf(LoginUtil.getLoginId())));
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("获取用户信息失败");
        }
    }



/**
 * 批量获取用户信息
 *//*

    @RequestMapping("listByIds")
    public Result<List<AuthUserDTO>> listUserInfoByIds(@RequestBody List<String> userNameList) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.listUserInfoByIds.dto:{}", JSONUtil.toJsonStr(userNameList));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(userNameList), "id集合不能为空");

            List<AuthUser> userInfos = authUserDomainService.listUserInfoByIds(userNameList);

            return Result.ok(BeanUtil.copyToList(userInfos, AuthUserDTO.class));
        } catch (Exception e) {
            log.error("UserController.listUserInfoByIds.error:{}", e.getMessage(), e);
            return Result.fail("批量获取用户信息失败");
        }
    }
*/

    /**
     * 用户退出
     */
    @RequestMapping("logOut")
    public Result logOut(@RequestParam("id") String id) {
        try {
            log.info("UserController.logOut.userName:{}", id);
            Preconditions.checkArgument(!StringUtils.isBlank(id), "用户名不能为空");
            StpUtil.logout(id);
            return Result.ok();
        } catch (Exception e) {
            log.error("UserController.logOut.error:{}", e.getMessage(), e);
            return Result.fail("用户登出失败");
        }
    }

//    /**
//     * 删除用户
//     */
//    @RequestMapping("delete")
//    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
//        try {
//            if (log.isInfoEnabled()) {
//                log.info("UserController.delete.dto:{}", JSONUtil.toJsonStr(authUserDTO));
//            }
//            AuthUser authUser = BeanUtil.copyProperties(authUserDTO, AuthUser.class);
//            return Result.ok(authUserDomainService.update(authUser));
//        } catch (Exception e) {
//            log.error("UserController.update.error:{}", e.getMessage(), e);
//            return Result.fail("删除用户信息失败");
//        }
//    }
//
//    private void checkUserInfo(@RequestBody AuthUserDTO authUserDTO) {
//        Preconditions.checkArgument(!StringUtils.isBlank(authUserDTO.getUserName()), "用户名不能为空");
//    }
//
    /**
     * 用户启用/禁用
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody UserAccount userAccount) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.changeStatus.dto:{}", JSONUtil.toJsonStr(userAccount));
            }
            Preconditions.checkNotNull(userAccount.getStatus(), "用户状态不能为空");
            return Result.ok(userInfoService.update(userAccount));
        } catch (Exception e) {
            log.error("UserController.changeStatus.error:{}", e.getMessage(), e);
            return Result.fail("启用/禁用用户信息失败");
        }
    }

    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode, @RequestParam("role") String role) {
        try {
            Preconditions.checkArgument(!StringUtils.isBlank(validCode), "验证码不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(role), "身份不能为空!");
            return Result.ok(authUserDomainService.doLogin(validCode, role));
        } catch (Exception e) {
            log.error("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("用户登录失败");
        }
    }

    @PostMapping("sendMsg")
    public Result sendMsg(@RequestParam("email") String email) throws MessagingException {
        if (StringUtils.isEmpty(email)) {
            return Result.fail("短信发送失败");
        }
//      2.随机生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

//      3.调用阿里云提供的短信服务
        emailApi.sendHtmlEmail("云求职", "<h1>您好，你的登录验证码是" + code + "<h1/>", email);

        String numKey = redisUtil.buildKey(PHONE_PREFIX, String.valueOf(code));

        redisUtil.setNx(numKey, email, 5L, TimeUnit.MINUTES);
        return Result.ok();
    }

    /**
     * @param email
     * @param code
     * @return {@link Result }<{@link SaTokenInfo }>
     * 短信登录
     */
    @RequestMapping("email/doLogin")
    public Result<SaTokenInfo> emailDoLogin(@RequestParam("email") String email, @RequestParam("code") String code) {
        try {
            Preconditions.checkArgument(!StringUtils.isBlank(email), "邮箱不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(code), "短信验证码不能为空!");
            return Result.ok(authUserDomainService.emailDoLogin(email, code));
        } catch (Exception e) {
            log.error("UserController.phoneDoLogin.error:{}", e.getMessage(), e);
            return Result.fail("短信登录失败");
        }
    }
    /**
     * @param username
     * @param password
     * @return {@link Result }<{@link SaTokenInfo }>
     * 管理员登录
     */
    @RequestMapping("admin/doLogin")
    public Result<SaTokenInfo> adminDoLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
        try {
            Preconditions.checkArgument(!StringUtils.isBlank(username), "账号不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(password), "密码不能为空!");
            return Result.ok(authUserDomainService.adminDoLogin(username, password));
        } catch (Exception e) {
            log.error("UserController.phoneDoLogin.error:{}", e.getMessage(), e);
            return Result.fail("登录失败");
        }
    }
    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

    @Autowired
    private UserInfoServiceImpl userInfoService;

    /**
     * 根据用户账户ID查询求职者信息
     */
    @GetMapping("/jobSeeker/{userId}")
    public Result<JobSeeker> getJobSeekerByUserId(@PathVariable("userId") Long userId) {
        return Result.ok(userInfoService.getJobSeekerByUserId(userId));
    }
    /**
     * 获取用户信息
     */

    @RequestMapping("allUser")
    public Result<List<UserAccount>> allUser(  ) {
        try {
            return Result.ok(userInfoService.getallUser());
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("获取用户信息失败");
        }
    }

    /**
     * 分页查询用户列表
     * @param page 当前页码
     * @param pageSize 每页大小
     * @param username 用户名
     * @param email 邮箱
     * @param userType 用户类型
     * @param status 状态
     */
    @GetMapping("getUserList")
    public Result<IPage<UserAccount>> getUserList(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "userType", required = false) Integer userType,
            @RequestParam(value = "status", required = false) Integer status) {
        try {
            Page<UserAccount> pageParam = new Page<>(page, pageSize);
            IPage<UserAccount> result = userInfoService.getUserList(pageParam, username, email, userType, status);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("UserController.getUserList.error:{}", e.getMessage(), e);
            return Result.fail("获取用户列表失败");
        }
    }
    /**
     * 根据用户账户ID查询公司信息
     */
    @GetMapping("/company/{userId}")
    public Result<Company> getCompanyByUserId(@PathVariable("userId") Long userId) {
        return Result.ok(userInfoService.getCompanyByUserId(userId));
    }

    /**
     * 根据用户账户ID查询HR信息
     */
    @GetMapping("/hr/{userId}")
    public Result<CompanyHr> getHrByUserId(@PathVariable("userId") Long userId) {
        return Result.ok(userInfoService.getHrByUserId(userId));
    }

    /**
     * 根据公司ID查询该公司的所有HR
     */
    @GetMapping("/company/{companyId}/hrs")
    public List<CompanyHr> getHrsByCompanyId(@PathVariable("companyId") Long companyId) {
        return userInfoService.getHrsByCompanyId(companyId);
    }

    /**
     * 根据HR的用户账户ID查询对应的公司信息
     */
    @GetMapping("/hr/{userId}/company")
    public Result<Company> getCompanyByHrUserId(@PathVariable("userId") Long hrId) {
        return Result.ok(userInfoService.getCompanyByHrUserId(hrId));
    }

    /**
     * 根据用户ID获取用户账户信息
     */
    @GetMapping("/account/{userId}")
    public UserAccount getUserAccountById(@PathVariable("userId") Long userId){
        return userInfoService.getUserAccountById(userId);
    }

}
